import {login, register, resetPassword} from '../api/users'

const state = {
    token: localStorage.getItem('token') || null,
    user: null
}

const mutations = {
    SET_TOKEN(state, token) {
        state.token = token
        localStorage.setItem('token', token)
    },
    SET_USER(state, user) {
        state.user = user
    },
    CLEAR_AUTH(state) {
        state.token = null
        state.user = null
        localStorage.removeItem('token')
    }
}

const actions = {
    async login({ commit }, credentials) {
        try {
            const res = await login(credentials)

            // 确保后端返回成功的状态
            if (res.data && res.data.code === 200) {
                commit('SET_TOKEN', res.data.data.token)
                commit('SET_USER', {
                    userName: res.data.data.userName,
                    userId: res.data.data.userId
                })
                return res.data  // 返回登录成功的数据
            } else {
                throw new Error(res.data.msg || '登录失败')
            }
        } catch (err) {
            // 错误处理
            return Promise.reject(err)
        }
    },

    async register(_, userData) {
        return register(userData) // 移除无用的 try/catch，已在 API 层处理
    },

    async resetPassword(_, userData) {
        // 添加密码重置逻辑
        return resetPassword(userData)
    },

    logout({ commit }) {
        commit('CLEAR_AUTH')
    }
}

const getters = {
    isAuthenticated: state => !!state.token,
    currentUser: state => state.user
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}
